<?php

namespace App\Models;

use Illuminate\Support\Collection;

class GoodsCat extends Model
{
    protected $table = 'yf_goods_cat';
    protected $primaryKey = 'cat_id';
    public $timestamps = false;
    protected $guarded = ['cat_id'];

    public function children()
    {
        return $this->hasMany(GoodsCat::class, 'cat_parent_id', 'cat_id');
    }

    public function mbCatImage()
    {
        return $this->hasOne(MbCatImage::class, 'cat_id', 'cat_id');
    }

    public function goodsType()
    {
        return $this->hasOne(GoodsType::class, 'type_id', 'type_id');
    }

    public static function getCategoriesByParentId(int $parentId = 0, ...$columns) : Collection
    {
        return self::where('cat_parent_id', $parentId)
            ->when($columns, function ($query) use ($columns) {
                return $query->select($columns);
            }, function ($query) {
                return $query->select('cat_id', 'cat_name');
            })
            ->where('cat_name', '<>', 'APP下载')
            ->oldest('cat_displayorder')
            ->get();
    }

    public function getChildrenTree() : Collection
    {
        $items = [];
        $this->children->each(function ($c1, $i1) use (&$items) {
            $items[$i1] = $c1->only('cat_id', 'cat_name', 'type_id');
            $c1->children->each(function ($c2, $i2) use (&$items, $c1, $i1) {
                $items[$i1]['child'][$i2] = $c2->toArray();
                $items[$i1]['child'][$i2]['cat_image'] = $c2->mbCatImage->mb_cat_image;
            });
        });

        return new Collection($items);
    }

    public function getAllChildrenIds() : array
    {
        $items = $this->children->pluck('cat_id')->toArray();

        $this->children->each(function ($child) use (&$items) {
            array_push($items, $child->children->pluck('cat_id')->toArray());
        });

        return $items;
    }

    public function brands() : array
    {
        return $this->goodsType ?
            ($this->goodsType->goodsBrands ?
                $this->goodsType->goodsBrands->makeHidden('pivot')->toArray() : []) : [];
    }
}
